﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PeoplesJukebox.Core.Interfaces;
using PeoplesJukebox.Core.MediaItems;
using System.Threading;
using PeoplesJukebox.Core.Logging;
using config = PeoplesJukebox.Core.Configuration;
using System.Reflection;
using media = System.Media;

namespace PeoplesJukebox.Core.Players
{
    public class SoundPlayer : IMediaPlayer
    {
        private static Track _currentTrack;
        private static int _mediaErrorCount;
        private static media.SoundPlayer _player;

        static SoundPlayer()
        {
            _mediaErrorCount = 0;
            _player = new media.SoundPlayer();
        }

        public Track CurrentTrack
        {
            get { return _currentTrack; }
        }

        public void Start()
        {
            PlayNext();
        }

        static void PlayNext()
        {
            Track nextTrack = PeoplesJukeboxService.GetNextTrack();
            if (nextTrack != null)
            {
                try
                {
                    StopInternal();
                    ThreadPool.QueueUserWorkItem(PlayCallback, nextTrack);                    
                }
                catch (Exception ex)
                {
                    Log.Error("SoundPlayer.PlayNext errored: {0}", ex.Message);
                }
                _currentTrack = nextTrack;
            }
        }

        static void PlayCallback(object state)
        {
            Track nextTrack = state as Track;
            _player.SoundLocation = nextTrack.Uri;
            Log.Info("SoundPlayer.PlayCallback, new URL={0}", nextTrack.Uri);
            _player.PlaySync();
            Log.Info("SoundPlayer.PlayCallback, called PlaySync()");
            PlayNext();
        }

        public void Skip()
        {
            PlayNext();
        }

        public void Stop()
        {
            StopInternal();
        }

        static void StopInternal()
        {
            if (_player != null)
            {
                _player.Stop();
            }
        }
    }
}
